import 'dart:convert';

import 'package:dio/dio.dart';
class CacheResponse {
  late String uniqUrl;
  late Response response;
  late DateTime dateTime;
  CacheResponse.build(this.uniqUrl, this.response,this.dateTime);

  /// 将 CacheResponse 转换为 JSON 字符串
  String toJsonString() {
    return jsonEncode({
      'uniqUrl': uniqUrl,
      'response': {
        'data': response.data,
        'statusCode': response.statusCode,
        'headers': response.headers.map,
        'extra': response.extra,
        'requestOptions': {
          'path': response.requestOptions.path,
          'method': response.requestOptions.method,
          'headers': response.requestOptions.headers,
        },
      },
      'dateTime': dateTime.toIso8601String(),
    });
  }

  /// 从 JSON 字符串恢复 CacheResponse（不完整重建 Dio.Response，仅恢复核心数据）
  static CacheResponse fromJsonString(String jsonStr) {
    final map = jsonDecode(jsonStr);
    final responseMap = map['response'];

    final response = Response(
      data: responseMap['data'],
      statusCode: responseMap['statusCode'],
      headers: Headers.fromMap(Map<String, List<String>>.from(
        (responseMap['headers'] as Map).map((k, v) => MapEntry(k, List<String>.from(v))),
      )),
      requestOptions: RequestOptions(
        path: responseMap['requestOptions']['path'],
        method: responseMap['requestOptions']['method'],
        headers: Map<String, dynamic>.from(responseMap['requestOptions']['headers']),
      ),
      extra: Map<String, dynamic>.from(responseMap['extra'] ?? {}),
    );

    return CacheResponse.build(
      map['uniqUrl'],
      response,
      DateTime.parse(map['dateTime']),
    );
  }
}